<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="SwiftUI," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="这个高级SwiftUI动画系列的第五部分将探索Canvas视图。从技术上讲，它不是一个动画视图，但当它与第四部分的 TimelineView 结合时，它带来了很多有趣的可能性，正如这个数字雨的例子所示。  我不得不把这篇文章推迟几周，因为 Canvas 视图有点不稳定。我们仍然处于测试阶段，所以这是可以预期的。然而，该视图产生的崩溃使这里的一些例子无法分享。虽然不是所有的问题都得到了解决，但现在每">
<meta name="keywords" content="SwiftUI">
<meta property="og:type" content="article">
<meta property="og:title" content="SwiftUI 动画进阶 — Part 5：Canvas">
<meta property="og:url" content="https://fanbaoying.github.io/SwiftUI-动画进阶-—-Part-5：Canvas/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="这个高级SwiftUI动画系列的第五部分将探索Canvas视图。从技术上讲，它不是一个动画视图，但当它与第四部分的 TimelineView 结合时，它带来了很多有趣的可能性，正如这个数字雨的例子所示。  我不得不把这篇文章推迟几周，因为 Canvas 视图有点不稳定。我们仍然处于测试阶段，所以这是可以预期的。然而，该视图产生的崩溃使这里的一些例子无法分享。虽然不是所有的问题都得到了解决，但现在每">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/120523a00d0eae25fce6b66bf2cbd5af.gif">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/5f98cc102dc7e6b6fba0ad5fca2c02ac.png">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/555ea370f0cd7dbabeb00b8130629f0c.png">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/25c25b8a2fce3d78473c7971e7ee556e.png">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/1279412a14866c8db5c9860d2a0522a8.gif">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/234d739c8d952cad3d383d0f2db9a55a.png">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/ef94d171903c01b0297711d9e3d51929.gif">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/f6a032bc77438cca45f5e308e7f89e8f.gif">
<meta property="og:image" content="https://images.xiaozhuanlan.com/photo/2022/991bc2c8ebb00060bd77b6345cf290a6.gif">
<meta property="og:updated_time" content="2022-04-06T02:33:15.419Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SwiftUI 动画进阶 — Part 5：Canvas">
<meta name="twitter:description" content="这个高级SwiftUI动画系列的第五部分将探索Canvas视图。从技术上讲，它不是一个动画视图，但当它与第四部分的 TimelineView 结合时，它带来了很多有趣的可能性，正如这个数字雨的例子所示。  我不得不把这篇文章推迟几周，因为 Canvas 视图有点不稳定。我们仍然处于测试阶段，所以这是可以预期的。然而，该视图产生的崩溃使这里的一些例子无法分享。虽然不是所有的问题都得到了解决，但现在每">
<meta name="twitter:image" content="https://images.xiaozhuanlan.com/photo/2022/120523a00d0eae25fce6b66bf2cbd5af.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/SwiftUI-动画进阶-—-Part-5：Canvas/"/>





  <title>SwiftUI 动画进阶 — Part 5：Canvas | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/SwiftUI-动画进阶-—-Part-5：Canvas/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SwiftUI 动画进阶 — Part 5：Canvas</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-04-06T10:31:33+08:00">
                2022-04-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SwiftUI-动画/" itemprop="url" rel="index">
                    <span itemprop="name">SwiftUI 动画</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 4,588字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 20分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这个高级SwiftUI动画系列的第五部分将探索Canvas视图。从技术上讲，它不是一个动画视图，但当它与第四部分的 <code>TimelineView</code> 结合时，它带来了很多有趣的可能性，正如这个数字雨的例子所示。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/120523a00d0eae25fce6b66bf2cbd5af.gif" alt=""></p>
<p>我不得不把这篇文章推迟几周，因为 Canvas 视图有点不稳定。我们仍然处于测试阶段，所以这是可以预期的。然而，该视图产生的崩溃使这里的一些例子无法分享。虽然不是所有的问题都得到了解决，但现在每个例子都能顺利运行。在文章的最后，我将指出我找到的一些解决方法。</p>
<a id="more"></a>
<h1 id="一个简单的-Canvas"><a href="#一个简单的-Canvas" class="headerlink" title="一个简单的 Canvas"></a>一个简单的 Canvas</h1><p>简而言之，画布<code>Canvas</code> 是一个 SwiftUI 视图，它从一个渲染闭包中获得绘制指令。与 SwiftUI API 中的大多数闭包不同，它不是一个视图生成器。这意味着我们可以使用 Swift 语言且没有任何限制。</p>
<p>该闭包接收两个参数：上下文<code>context</code> 和 尺寸<code>size</code>。上下文使用一个新的 SwiftUI 类型 <code>GraphicsContext</code>，它包含了很多方法和属性，可以让我们绘制任何东西。下面是一个关于如何使用 <code>Canvas</code> 的基本例子。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/5f98cc102dc7e6b6fba0ad5fca2c02ac.png" alt=""></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ContentView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            <span class="keyword">let</span> rect = <span class="type">CGRect</span>(origin: .zero, size: size).insetBy(dx: <span class="number">25</span>, dy: <span class="number">25</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Path</span></span><br><span class="line">            <span class="keyword">let</span> path = <span class="type">Path</span>(roundedRect: rect, cornerRadius: <span class="number">35.0</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Gradient</span></span><br><span class="line">            <span class="keyword">let</span> gradient = <span class="type">Gradient</span>(colors: [.green, .blue])</span><br><span class="line">            <span class="keyword">let</span> from = rect.origin</span><br><span class="line">            <span class="keyword">let</span> to = <span class="type">CGPoint</span>(x: rect.width + from.x, y: rect.height + from.y)</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// Stroke path</span></span><br><span class="line">            context.stroke(path, with: .color(.blue), lineWidth: <span class="number">25</span>)</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// Fill path</span></span><br><span class="line">            context.fill(path, with: .linearGradient(gradient,</span><br><span class="line">                                                     startPoint: from,</span><br><span class="line">                                                     endPoint: to))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Canvas</code>初始值设定项还有其他参数（不透明度<code>opaque</code>、颜色模式<code>colorMode</code>和渲染同步<code>rendersAsynchronously</code>）。请参阅<a href="https://developer.apple.com/documentation/swiftui/canvas/init(opaque:colormode:rendersasynchronously:renderer:symbols:" target="_blank" rel="noopener">苹果的文档</a>)以了解更多信息。</p>
<h1 id="图形上下文-GraphicsContext"><a href="#图形上下文-GraphicsContext" class="headerlink" title="图形上下文 - GraphicsContext"></a>图形上下文 - GraphicsContext</h1><p><code>GraphicsContext</code>有很多方法和属性，但我并不打算把这篇文章作为一个参考，把它们z一一列出。这是一个很长的列表，可能会让人有点不知所措。然而，当我在更新<a href="https://swiftui-lab.com/companion/" target="_blank" rel="noopener">Companion for SwiftUI app</a> 时，我确实不得不去浏览所有这些方法。这让我有了一个整体的想法。我将尝试对现有的东西进行分类，这样你就能得到同样的东西。</p>
<ul>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#paths" target="_blank" rel="noopener">Drawing Paths</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#images" target="_blank" rel="noopener">Drawing Images and Text</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#symbols" target="_blank" rel="noopener">Drawing Symbols (aka SwiftUI views)</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#mutating" target="_blank" rel="noopener">Mutating the Graphics Context</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#coregraphics" target="_blank" rel="noopener">Reusing CoreGraphics Code</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#animating" target="_blank" rel="noopener">Animating the Canvas</a></li>
<li><a href="https://swiftui-lab.com/swiftui-animations-part5/#crashes" target="_blank" rel="noopener">Canvas Crashes</a></li>
</ul>
<h1 id="路径-Paths"><a href="#路径-Paths" class="headerlink" title="路径 - Paths"></a>路径 - Paths</h1><p>绘制路径的第一件事是创建它。从 SwiftUI 的第一个版本开始，路径可以通过多种方式创建和修改。一些可用的初始化器是：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> path = <span class="type">Path</span>(roundedRect: rect, cornerSize: <span class="type">CGSize</span>(width: <span class="number">10</span>, height: <span class="number">50</span>), style: .continuous)</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> cgPath = <span class="type">CGPath</span>(ellipseIn: rect, transform: <span class="literal">nil</span>)</span><br><span class="line"><span class="keyword">let</span> path = <span class="type">Path</span>(cgPath)</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> path = <span class="type">Path</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> points: [<span class="type">CGPoint</span>] = [</span><br><span class="line">        .<span class="keyword">init</span>(x: <span class="number">10</span>, y: <span class="number">10</span>),</span><br><span class="line">        .<span class="keyword">init</span>(x: <span class="number">0</span>, y: <span class="number">50</span>),</span><br><span class="line">        .<span class="keyword">init</span>(x: <span class="number">100</span>, y: <span class="number">100</span>),</span><br><span class="line">        .<span class="keyword">init</span>(x: <span class="number">100</span>, y: <span class="number">0</span>),</span><br><span class="line">    ]</span><br><span class="line">    </span><br><span class="line">    $<span class="number">0</span>.move(to: .zero)</span><br><span class="line">    $<span class="number">0</span>.addLines(points)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>路径也可以从一个 SwiftUI 形状中创建。<code>Shape</code> 协议有一个路径方法，你可以用它来创建一个 <code>path</code>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> path = <span class="type">Circle</span>().path(<span class="keyword">in</span>: rect)</span><br></pre></td></tr></table></figure>
<p> 当然，这也适用于自定义形状：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> path = <span class="type">MyCustomShape</span>().path(<span class="keyword">in</span>: rect)</span><br></pre></td></tr></table></figure>
<h2 id="填充路径"><a href="#填充路径" class="headerlink" title="填充路径"></a>填充路径</h2><p>要填充一个路径，请使用 <code>context.fill()</code> 方法：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fill(<span class="number">_</span> path: <span class="type">Path</span>, with shading: <span class="type">GraphicsContext</span>.<span class="type">Shading</span>, style: <span class="type">FillStyle</span> = <span class="type">FillStyle</span>())</span><br></pre></td></tr></table></figure>
<p>着色<code>shading</code>表示如何填充形状（用颜色、渐变、平铺图像等）。如果你需要指示要使用的样式，请使用<code>FillStyle</code>类型（即偶数奇数/反义属性）。</p>
<h2 id="路径描边-Stroke"><a href="#路径描边-Stroke" class="headerlink" title="路径描边 - Stroke"></a>路径描边 - Stroke</h2><p>要描画一个路径，请使用这些<code>GraphicsContext</code>方法中的一个:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">stroke(<span class="number">_</span> path: <span class="type">Path</span>, with shading: <span class="type">GraphicsContext</span>.<span class="type">Shading</span>, style: <span class="type">StrokeStyle</span>)</span><br><span class="line">stroke(<span class="number">_</span> path: <span class="type">Path</span>, with shading: <span class="type">GraphicsContext</span>.<span class="type">Shading</span>, lineWidth: <span class="type">CGFloat</span> = <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>你可以指定一个<code>shading</code>（颜色、渐变等）来表示如何描画路径。如果你需要指定破折号、线帽、连接等，请使用样式<code>style</code>。另外，你也可以只指定线宽。</p>
<p>关于如何描边和填充一个形状的完整例子，请看上面的例子（<strong>一个简单的 Canvas</strong>）。</p>
<h2 id="图片和文本-Image-amp-Text"><a href="#图片和文本-Image-amp-Text" class="headerlink" title="图片和文本 - Image &amp; Text"></a>图片和文本 - Image &amp; Text</h2><p>图像和文本是使用上下文<code>draw()</code>方法绘制的，有两个版本：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">draw(image_or_text, at point: <span class="type">CGPoint</span>, anchor: <span class="type">UnitPoint</span> = .center)</span><br><span class="line">draw(image_or_text, <span class="keyword">in</span> rect: <span class="type">CGRect</span>)</span><br></pre></td></tr></table></figure>
<p>在图像的情况下，第二个<code>draw()</code>版本有一个额外的可选参数，<code>style</code>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">draw(image, <span class="keyword">in</span> rect: <span class="type">CGRect</span>, style: <span class="type">FillStyle</span> = <span class="type">FillStyle</span>())</span><br></pre></td></tr></table></figure>
<p>在这些元素之一可以被绘制之前，它们必须被解析。通过解析，SwiftUI将考虑到环境（例如，颜色方案、显示分辨率等）。此外，解析这些元素会暴露出一些有趣的属性，这些属性可能会被进一步用于我们的绘制逻辑。例如，解析后的文本会告诉我们指定字体的最终尺寸。或者我们也可以在绘制之前改变已解析元素的阴影。要了解更多关于可用的属性和方法，请查看 <a href="https://developer.apple.com/documentation/swiftui/graphicscontext/resolvedimage" target="_blank" rel="noopener">ResolvedImage</a> 和 <a href="https://developer.apple.com/documentation/swiftui/graphicscontext/resolvedtext" target="_blank" rel="noopener">ResolvedText</a> 。</p>
<p>使用上下文的<code>resolve()</code>方法从<code>Image</code>中获得<code>ResolvedImage</code>，从<code>Text</code>中获得<code>ResolvedText</code>。</p>
<p>解析是可选的，<code>draw()</code>方法也接受<code>Image</code>和<code>Text</code>（而不是<code>ResolvedImage</code>和<code>ResolvedText</code>）。在这种情况下，<code>draw()</code>会自动解析它们。如果你对已解析的属性和方法没有任何用途，这很方便。</p>
<p>在这个例子中，文本被解决了。我们用它的大小来计算渐变，并用着色<code>shading</code>来应用这种渐变：</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/555ea370f0cd7dbabeb00b8130629f0c.png" alt=""></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="keyword">let</span> midPoint = <span class="type">CGPoint</span>(x: size.width/<span class="number">2</span>, y: size.height/<span class="number">2</span>)</span><br><span class="line">            <span class="keyword">let</span> font = <span class="type">Font</span>.custom(<span class="string">"Arial Rounded MT Bold"</span>, size: <span class="number">36</span>)</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">var</span> resolved = context.resolve(<span class="type">Text</span>(<span class="string">"Hello World!"</span>).font(font))</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">let</span> start = <span class="type">CGPoint</span>(x: (size.width - resolved.measure(<span class="keyword">in</span>: size).width) / <span class="number">2.0</span>, y: <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">let</span> end = <span class="type">CGPoint</span>(x: size.width - start.x, y: <span class="number">0</span>)</span><br><span class="line">            </span><br><span class="line">            resolved.shading = .linearGradient(<span class="type">Gradient</span>(colors: [.green, .blue]),</span><br><span class="line">                                               startPoint: start,</span><br><span class="line">                                               endPoint: end)</span><br><span class="line">            </span><br><span class="line">            context.draw(resolved, at: midPoint, anchor: .center)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="符号-Symbols"><a href="#符号-Symbols" class="headerlink" title="符号 - Symbols"></a>符号 - Symbols</h2><p>在谈<code>Canvas</code>时，符号<code>Symbols</code>指的只是任何的 SwiftUI。不要与SF符号相混淆，后者是完全不同的东西。<code>Canvas</code> 视图有一种引用 SwiftUI 视图的方式，将其解析为一个符号，然后绘制它。</p>
<p>要解决的视图是在<code>ViewBuilder</code>闭包中传递的，如下面的例子所示。为了引用一个视图，它需要被标记为一个唯一的可散列的标识符。请注意，一个被解析的符号可以在<code>Canvas</code>上绘制不止一次。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/25c25b8a2fce3d78473c7971e7ee556e.png" alt=""></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="keyword">let</span> r0 = context.resolveSymbol(id: <span class="number">0</span>)!</span><br><span class="line">            <span class="keyword">let</span> r1 = context.resolveSymbol(id: <span class="number">1</span>)!</span><br><span class="line">            <span class="keyword">let</span> r2 = context.resolveSymbol(id: <span class="number">2</span>)!</span><br><span class="line">            </span><br><span class="line">            context.draw(r0, at: .<span class="keyword">init</span>(x: <span class="number">10</span>, y: <span class="number">10</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r1, at: .<span class="keyword">init</span>(x: <span class="number">30</span>, y: <span class="number">20</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r2, at: .<span class="keyword">init</span>(x: <span class="number">50</span>, y: <span class="number">30</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r0, at: .<span class="keyword">init</span>(x: <span class="number">70</span>, y: <span class="number">40</span>), anchor: .topLeading)</span><br><span class="line"></span><br><span class="line">        &#125; symbols: &#123;</span><br><span class="line">            <span class="type">RoundedRectangle</span>(cornerRadius: <span class="number">10.0</span>).fill(.cyan)</span><br><span class="line">                .frame(width: <span class="number">100</span>, height: <span class="number">50</span>)</span><br><span class="line">                .tag(<span class="number">0</span>)</span><br><span class="line">            </span><br><span class="line">            <span class="type">RoundedRectangle</span>(cornerRadius: <span class="number">10.0</span>).fill(.blue)</span><br><span class="line">                .frame(width: <span class="number">100</span>, height: <span class="number">50</span>)</span><br><span class="line">                .tag(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">            <span class="type">RoundedRectangle</span>(cornerRadius: <span class="number">10.0</span>).fill(.indigo)</span><br><span class="line">                .frame(width: <span class="number">100</span>, height: <span class="number">50</span>)</span><br><span class="line">                .tag(<span class="number">2</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>ViewBuilder</code>也可以使用一个<code>ForEach</code>。同样的例子可以改写成这样:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> colors: [<span class="type">Color</span>] = [.cyan, .blue, .indigo]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="keyword">let</span> r0 = context.resolveSymbol(id: <span class="number">0</span>)!</span><br><span class="line">            <span class="keyword">let</span> r1 = context.resolveSymbol(id: <span class="number">1</span>)!</span><br><span class="line">            <span class="keyword">let</span> r2 = context.resolveSymbol(id: <span class="number">2</span>)!</span><br><span class="line">            </span><br><span class="line">            context.draw(r0, at: .<span class="keyword">init</span>(x: <span class="number">10</span>, y: <span class="number">10</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r1, at: .<span class="keyword">init</span>(x: <span class="number">30</span>, y: <span class="number">20</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r2, at: .<span class="keyword">init</span>(x: <span class="number">50</span>, y: <span class="number">30</span>), anchor: .topLeading)</span><br><span class="line">            context.draw(r0, at: .<span class="keyword">init</span>(x: <span class="number">70</span>, y: <span class="number">40</span>), anchor: .topLeading)</span><br><span class="line"></span><br><span class="line">        &#125; symbols: &#123;</span><br><span class="line">            <span class="type">ForEach</span>(<span class="type">Array</span>(colors.enumerated()), id: \.<span class="number">0</span>) &#123; n, <span class="built_in">c</span> <span class="keyword">in</span></span><br><span class="line">                <span class="type">RoundedRectangle</span>(cornerRadius: <span class="number">10.0</span>).fill(<span class="built_in">c</span>)</span><br><span class="line">                    .frame(width: <span class="number">100</span>, height: <span class="number">50</span>)</span><br><span class="line">                    .tag(n)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="符号的动画-Animated-Symbols"><a href="#符号的动画-Animated-Symbols" class="headerlink" title="符号的动画 - Animated Symbols"></a>符号的动画 - Animated Symbols</h2><p>当我测试如果视图作为一个符号被解析为动画，会发生什么时，我感到非常惊喜。你猜怎么着，画布会不断地重绘它以保持动画效果。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/1279412a14866c8db5c9860d2a0522a8.gif" alt=""></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ContentView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="keyword">let</span> symbol = context.resolveSymbol(id: <span class="number">1</span>)!</span><br><span class="line">            </span><br><span class="line">            context.draw(symbol, at: <span class="type">CGPoint</span>(x: size.width/<span class="number">2</span>, y: size.height/<span class="number">2</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">        &#125; symbols: &#123;</span><br><span class="line">            <span class="type">SpinningView</span>()</span><br><span class="line">                .tag(<span class="number">1</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SpinningView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> flag = <span class="literal">true</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Text</span>(<span class="string">""</span>)</span><br><span class="line">            .font(.custom(<span class="string">"Arial"</span>, size: <span class="number">72</span>))</span><br><span class="line">            .rotationEffect(.degrees(flag ? <span class="number">0</span> : <span class="number">360</span>))</span><br><span class="line">            .onAppear&#123;</span><br><span class="line">                withAnimation(.linear(duration: <span class="number">1.0</span>).repeatForever(autoreverses: <span class="literal">false</span>)) &#123;</span><br><span class="line">                    flag.toggle()</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="改变图形上下文"><a href="#改变图形上下文" class="headerlink" title="改变图形上下文"></a>改变图形上下文</h1><p>图形上下文可以被改变，使用以下方法之一：</p>
<ul>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/addfilter(_:options:" target="_blank" rel="noopener">addFilter</a>?changes=l_7_8_3)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/clip(to:style:options:" target="_blank" rel="noopener">clip</a>)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/cliptolayer(opacity:options:content:" target="_blank" rel="noopener">clipToLayer</a>/)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/concatenate(_:" target="_blank" rel="noopener">concatenate</a>)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/rotate(by:" target="_blank" rel="noopener">rotate</a>)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/scaleby(x:y:" target="_blank" rel="noopener">scaleBy</a>)</li>
<li><a href="https://developer.apple.com/documentation/swiftui/graphicscontext/translateby(x:y:" target="_blank" rel="noopener">translateBy</a>)</li>
</ul>
<p>如果你熟悉 AppKit 的 <code>NSGraphicContext</code> 或 CoreGraphic 的 <code>CGContext</code>，你可能习惯于从堆栈中推送（保存）和弹出（恢复）图形上下文状态。Canvas GraphicsContext 的工作方式有些不同，如果你想对上下文做一个临时的改变，你有好几个选择。</p>
<p>为了说明这一点，让我们看看下面的例子。我们需要用三种颜色画三座房子。只有中间的房子，需要被模糊化：</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/234d739c8d952cad3d383d0f2db9a55a.png" alt=""></p>
<p>下面的所有例子将使用以下<code>CGPoint</code>扩展：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">CGPoint</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> +<span class="params">(lhs: CGPoint, rhs: CGPoint)</span></span> -&gt; <span class="type">CGPoint</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="type">CGPoint</span>(x: lhs.x + rhs.x, y: lhs.y + rhs.y)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> -<span class="params">(lhs: CGPoint, rhs: CGPoint)</span></span> -&gt; <span class="type">CGPoint</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="type">CGPoint</span>(x: lhs.x - rhs.x, y: lhs.y - rhs.y)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有三种实现相同结果的方法：</p>
<h4 id="1、通过对相应操作排序"><a href="#1、通过对相应操作排序" class="headerlink" title="1、通过对相应操作排序"></a>1、通过对相应操作排序</h4><p>在可能的情况下，你可以选择以一种适合你的方式对绘制操作进行排序。在这种情况下，最后绘制模糊的房子，就能解决问题。否则，只要你添加了模糊过滤器，所有的绘制操作都会继续模糊。</p>
<p>有时这可能是行不通的，即使可以，也可能变成难以阅读的代码。如果是这种情况，请检查其他选项。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment">// All drawing is done at x4 the size</span></span><br><span class="line">            context.scaleBy(x: <span class="number">4</span>, y: <span class="number">4</span>)</span><br><span class="line"></span><br><span class="line">            <span class="keyword">let</span> midpoint = <span class="type">CGPoint</span>(x: size.width / (<span class="number">2</span> * <span class="number">4</span>), y: size.height / (<span class="number">2</span> * <span class="number">4</span>))</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">var</span> house = context.resolve(<span class="type">Image</span>(systemName: <span class="string">"house.fill"</span>))</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Left house</span></span><br><span class="line">            house.shading = .color(.red)</span><br><span class="line">            context.draw(house, at: midpoint - <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Right house</span></span><br><span class="line">            house.shading = .color(.blue)</span><br><span class="line">            context.draw(house, at: midpoint + <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// Center house</span></span><br><span class="line">            context.addFilter(.blur(radius: <span class="number">1.0</span>, options: .dithersResult), options: .linearColor)</span><br><span class="line">            house.shading = .color(.green)</span><br><span class="line">            context.draw(house, at: midpoint, anchor: .center)</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2、通过拷贝上下文"><a href="#2、通过拷贝上下文" class="headerlink" title="2、通过拷贝上下文"></a>2、通过拷贝上下文</h3><p>由于图形上下文是一个值类型，你可以简单地创建一个副本。在副本上所做的所有改变，都不会影响到原始的上下文。一旦你完成了，你就可以继续在原始（未改变的）上下文上绘图。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment">// All drawing is done at x4 the size</span></span><br><span class="line">            context.scaleBy(x: <span class="number">4</span>, y: <span class="number">4</span>)</span><br><span class="line"></span><br><span class="line">            <span class="keyword">let</span> midpoint = <span class="type">CGPoint</span>(x: size.width / (<span class="number">2</span> * <span class="number">4</span>), y: size.height / (<span class="number">2</span> * <span class="number">4</span>))</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">var</span> house = context.resolve(<span class="type">Image</span>(systemName: <span class="string">"house.fill"</span>))</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Left house</span></span><br><span class="line">            house.shading = .color(.red)</span><br><span class="line">            context.draw(house, at: midpoint - <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Center house</span></span><br><span class="line">            <span class="keyword">var</span> blurContext = context</span><br><span class="line">            </span><br><span class="line">            blurContext.addFilter(.blur(radius: <span class="number">1.0</span>, options: .dithersResult), options: .linearColor)</span><br><span class="line">            house.shading = .color(.green)</span><br><span class="line">            blurContext.draw(house, at: midpoint, anchor: .center)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Right house</span></span><br><span class="line">            house.shading = .color(.blue)</span><br><span class="line">            context.draw(house, at: midpoint + <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3、通过使用图层上下文"><a href="#3、通过使用图层上下文" class="headerlink" title="3、通过使用图层上下文"></a>3、通过使用图层上下文</h3><p>最后，你可以使用 <code>context</code> 的方法： <code>drawLayer</code>。该方法有一个闭包，接收一个你可以使用的上下文的副本。所有对图层上下文的改变都不会影响原始的上下文：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment">// All drawing is done at x4 the size</span></span><br><span class="line">            context.scaleBy(x: <span class="number">4</span>, y: <span class="number">4</span>)</span><br><span class="line"></span><br><span class="line">            <span class="keyword">let</span> midpoint = <span class="type">CGPoint</span>(x: size.width / (<span class="number">2</span> * <span class="number">4</span>), y: size.height / (<span class="number">2</span> * <span class="number">4</span>))</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">var</span> house = context.resolve(<span class="type">Image</span>(systemName: <span class="string">"house.fill"</span>))</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Left house</span></span><br><span class="line">            house.shading = .color(.red)</span><br><span class="line">            context.draw(house, at: midpoint - <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Center house</span></span><br><span class="line">            context.drawLayer &#123; layerContext <span class="keyword">in</span></span><br><span class="line">                layerContext.addFilter(.blur(radius: <span class="number">1.0</span>, options: .dithersResult), options: .linearColor)</span><br><span class="line">                house.shading = .color(.green)</span><br><span class="line">                layerContext.draw(house, at: midpoint, anchor: .center)</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// Right house</span></span><br><span class="line">            house.shading = .color(.blue)</span><br><span class="line">            context.draw(house, at: midpoint + <span class="type">CGPoint</span>(x: house.size.width, y: <span class="number">0</span>), anchor: .center)</span><br><span class="line"></span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="重用-CoreGraphics-代码"><a href="#重用-CoreGraphics-代码" class="headerlink" title="重用 CoreGraphics 代码"></a>重用 CoreGraphics 代码</h1><p>如果你已经有使用 <code>CoreGraphics</code> 的绘制代码，你可以使用它。<code>Canvas</code>上下文有一个<code>withCGContext</code>方法，可以在如下这种情况下拯救你：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ExampleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">Canvas</span> &#123; context, size <span class="keyword">in</span></span><br><span class="line">            </span><br><span class="line">            context.withCGContext &#123; cgContext <span class="keyword">in</span></span><br><span class="line">                </span><br><span class="line">                <span class="comment">// CoreGraphics code here</span></span><br><span class="line">                </span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="对画布进行动画处理"><a href="#对画布进行动画处理" class="headerlink" title="对画布进行动画处理"></a>对画布进行动画处理</h2><p>通过将<code>Canvas</code>包裹在<code>TimelineView</code>内，我们可以实现一些相当有趣的动画。基本上，每一次时间线的更新，你都有机会绘制一个新的动画帧。</p>
<p>文章的其余部分假定你已经熟悉<code>TimelineView</code>，但如果你不熟悉，你可以查看本系列的<a href="https://swiftui-lab.com/swiftui-animations-part4/" target="_blank" rel="noopener">第四部分</a>来了解更多。</p>
<p>在下面的例子中，我们的 <code>Canvas</code> 绘制了一个给定日期的模拟时钟。通过将<code>Canvas</code>放在<code>TimelineView</code>内，并使用时间线更新日期，我们得到了动画时钟。以下屏幕截图的一部分是加速的，以显示分针和时针是如何移动的，否则就不容易观察到效果：</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/ef94d171903c01b0297711d9e3d51929.gif" alt=""></p>
<p>当我们用 <code>Canvas</code> 创建动画时，通常会使用时间线时间表的 <code>.animation</code>。这可以尽可能快地更新，每秒重绘我们的 <code>Canvas</code> 几次。然而，在可能的情况下，我们应该使用 <code>minimumInterval</code> 参数来限制每秒的更新次数。这样对CPU的要求会低一些。例如，在这种情况下，使用<code>.animation</code>和<code>.animation(minimumInterval: 0.06)</code>在视觉上没有明显的区别。然而，在我的测试硬件上，CPU使用率从30%下降到14%。使用更高的最小间隔时间可能开始变得视觉上明显，所以你可能需要做一些错误的试验，以找到最佳值。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/f6a032bc77438cca45f5e308e7f89e8f.gif" alt=""></p>
<p>为了进一步提高性能，你应该考虑<code>Canvas</code>中是否有一些部分不需要不断重绘。在我们的例子中，只有时钟指针在移动，其他部分保持静止。因此，明智的做法是把它分成两个重叠的画布。一个画除了钟针以外的所有东西（在时间线视图之外），另一个只画钟针，在时间线视图之内。通过实施这一改变，CPU从16%下降到6%。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Clock</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">ZStack</span> &#123;</span><br><span class="line">            <span class="type">ClockFaceCanvas</span>()</span><br><span class="line">            </span><br><span class="line">            <span class="type">TimelineView</span>(.animation(minimumInterval: <span class="number">0.06</span>)) &#123; timeline <span class="keyword">in</span></span><br><span class="line">                <span class="type">ClockHandsCanvas</span>(date: timeline.date)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过仔细分析我们的画布，并做了些许改动，我们成功地将CPU的使用率提高到了5倍（从30%降到6%）。顺便说一下，如果你能接受每秒更新的秒针，你将进一步减少CPU的使用，使其低于1%。你应该通过测试来找到最适合你的效果。</p>
<p>该时钟的完整代码可以在<a href="https://gist.github.com/swiftui-lab/168d8bb3abbe894c9dbbac22fdfdec86" target="_blank" rel="noopener">这里</a>找到。</p>
<h3 id="分治"><a href="#分治" class="headerlink" title="分治"></a>分治</h3><p>一旦我们了解了<code>Canvas</code>，我们可能会想用它来画一切。然而，有时最好的选择是选择做什么和在哪里做。下面这个Matrix Digital Rain动画就是一个很好的例子。</p>
<p><img src="https://images.xiaozhuanlan.com/photo/2022/991bc2c8ebb00060bd77b6345cf290a6.gif" alt=""></p>
<p>数字雨的完整代码可以在<a href="https://gist.github.com/swiftui-lab/7f13f04e2d103e43685193eec0c33dd5" target="_blank" rel="noopener">这里</a>找到。</p>
<p>我们来分析一下其中的内容。我们有一列字符出现，字符数量增长，慢慢滑落，最后减少其字符，直到消失。每一列都是用渐变绘制的。还有一种深度感，通过使靠近观察者的柱子滑动得更快和稍大。为了增加效果，柱子越靠后，它就越显得失焦（模糊）。</p>
<p>在 <code>Canvas</code> 中实现所有这些要求是完全可能的。然而，如果我们把这些任务分割开来（分而治之），任务就会变得容易得多。正如我们在本文的符号的动画部分已经看到的，一个带动画的SwiftUI视图可以通过一个<code>draw()</code>调用被绘制到<code>Canvas</code>中。因此，并不是所有的东西都要在<code>Canvas</code>里面处理。</p>
<p>每一列都被实现为一个单独的SwiftUI视图。叠加字符和用渐变绘图是由视图处理的。当我们在画布上使用渐变时，起始/结束点或任何其他几何参数都是相对于整个画布的。对于柱状渐变，在视图中实现它比较容易，因为它将相对于视图的原点。</p>
<p>每一列都有许多参数：位置（x、y、z）、字符、从顶部删除多少个字符，等等。这些值在每次<code>TimelineView</code>更新后都会被变更。</p>
<p>最后，<code>Canvas</code>负责解析每个视图，在它们的（x，y）位置上绘制，并根据其z值添加模糊和缩放效果。我在代码中添加了一些注释，以帮助你浏览它，如果你有兴趣的话。</p>
<h1 id="Canvas-崩溃"><a href="#Canvas-崩溃" class="headerlink" title="Canvas 崩溃"></a>Canvas 崩溃</h1><p>不幸的是，在写这篇文章的时候，我遇到了 Canvas 的一些崩溃问题。幸运的是，它们在每个测试版中都有很大的改进。我希望在iOS15正式发布时，它们都能得到解决。这条信息通常是这样的。</p>
<blockquote>
<p>-[MTLDebugRenderCommandEncoder validateCommonDrawErrors:]:5252: failed assertion `Draw Errors Validation<br>Fragment Function(primitive_gradient_fragment): argument small[0] from buffer(3) with offset(65460) and length(65536) has space for 76 bytes, but argument has a length(96).</p>
</blockquote>
<p>我设法解决了这些崩溃的问题，至少使用了其中一个方法：</p>
<ul>
<li>减少绘图量。在数字雨的例子中，你可以减少列的数量。</li>
<li>使用更简单的渐变。最初，数字雨柱有三个颜色的渐变。当我把它减少到两个时，崩溃就消失了。</li>
<li>减少更新Canvas的频率。使用较慢的时间轴视图，可以防止崩溃。</li>
</ul>
<p>我并不是说你不能使用超过两种颜色的渐变，但这只是你可以考虑的一个地方，如果你发现自己处于Canvas崩溃的情况。如果这还不能解决你的问题，我建议你开始删除绘图操作，直到应用程序不再崩溃。这可以引导你找到导致崩溃的原因。一旦你知道是什么原因，你可以尝试用不同的方法来做。</p>
<p>如果你遇到这个问题，我鼓励你向苹果公司反馈。如果你愿意，你可以参考我的反馈：FB9363322。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>我希望这篇文章能帮助你为你的SwiftUI动画工具箱添加一个新的工具。第五部分的动画系列到此结束。至少在今年……谁知道WWDC’22会带来什么呢!</p>
<blockquote>
<p>译自 <a href="https://swiftui-lab.com/" target="_blank" rel="noopener">The SwiftUI Lab</a> 的 <a href="https://swiftui-lab.com/swiftui-animations-part5/" target="_blank" rel="noopener">Advanced SwiftUI Animations – Part 5: Canvas</a></p>
</blockquote>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/SwiftUI-动画进阶-—-Part-5：Canvas/">SwiftUI 动画进阶 — Part 5：Canvas</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年04月06日 - 10:04</p>
  <p><span>最后更新:</span>2022年04月06日 - 10:04</p>
  <p><span>原始链接:</span><a href="/SwiftUI-动画进阶-—-Part-5：Canvas/" title="SwiftUI 动画进阶 — Part 5：Canvas">https://fanbaoying.github.io/SwiftUI-动画进阶-—-Part-5：Canvas/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/SwiftUI-动画进阶-—-Part-5：Canvas/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SwiftUI/" rel="tag"><i class="fa fa-tag"></i> SwiftUI</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/高级-SwiftUI-动画进阶-——-Part4：TimelineView/" rel="next" title="高级 SwiftUI 动画进阶 —— Part4：TimelineView">
                <i class="fa fa-chevron-left"></i> 高级 SwiftUI 动画进阶 —— Part4：TimelineView
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Swift-中的幻象类型/" rel="prev" title="Swift 中的幻象类型">
                Swift 中的幻象类型 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一个简单的-Canvas"><span class="nav-number">1.</span> <span class="nav-text">一个简单的 Canvas</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#图形上下文-GraphicsContext"><span class="nav-number">2.</span> <span class="nav-text">图形上下文 - GraphicsContext</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路径-Paths"><span class="nav-number">3.</span> <span class="nav-text">路径 - Paths</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#填充路径"><span class="nav-number">3.1.</span> <span class="nav-text">填充路径</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路径描边-Stroke"><span class="nav-number">3.2.</span> <span class="nav-text">路径描边 - Stroke</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#图片和文本-Image-amp-Text"><span class="nav-number">3.3.</span> <span class="nav-text">图片和文本 - Image &amp; Text</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#符号-Symbols"><span class="nav-number">3.4.</span> <span class="nav-text">符号 - Symbols</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#符号的动画-Animated-Symbols"><span class="nav-number">3.5.</span> <span class="nav-text">符号的动画 - Animated Symbols</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#改变图形上下文"><span class="nav-number">4.</span> <span class="nav-text">改变图形上下文</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、通过对相应操作排序"><span class="nav-number">4.0.0.1.</span> <span class="nav-text">1、通过对相应操作排序</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、通过拷贝上下文"><span class="nav-number">4.0.1.</span> <span class="nav-text">2、通过拷贝上下文</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3、通过使用图层上下文"><span class="nav-number">4.0.2.</span> <span class="nav-text">3、通过使用图层上下文</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#重用-CoreGraphics-代码"><span class="nav-number">5.</span> <span class="nav-text">重用 CoreGraphics 代码</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#对画布进行动画处理"><span class="nav-number">5.1.</span> <span class="nav-text">对画布进行动画处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#分治"><span class="nav-number">5.1.1.</span> <span class="nav-text">分治</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Canvas-崩溃"><span class="nav-number">6.</span> <span class="nav-text">Canvas 崩溃</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
